﻿using Microsoft.AspNetCore.Mvc;
using Polly;
using XLAction.UploadFile.FileModel;

namespace XLAction.UploadFile.UploadService
{
    public class Uploadservice
    {
        public async Task<bool> RuleUploadFile(SliceFileInfo file)
        {
            //接口设置跨域 [EnableCors("AllowSpecificOrigin")]//允许跨域
            try
            {
                //获取上传文件路径
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload");

                //获取文件上传边界
                var files = Request.Form.Files;
                var buffer = new byte[file.Size];

                //获取文件名，并作为文件路径下的子目录
                var fileName = file.Name;
                //拼接成完整的文件路径
                path = path + "//" + fileName + "//";
                //判断路径是否存在
                if (!Directory.Exists(path))
                {
                    //创建文件路径
                    Directory.CreateDirectory(path);
                }

                //获取文件分片
                string filepath = path + "//" + file.Name + "^" + file.Number;
                using (var stream = new FileStream(filepath, FileMode.Append))
                {
                    //文件分片写入
                    await files[0].CopyToAsync(stream);
                }
                var filesList = Directory.GetFiles(Path.GetDirectoryName(path));

                //当顺序号等于分片总数量 合并文件
                if ((file.Number + 1) == file.Count || filesList.Length == file.Count)
                {
                    await MergeFile(file);
                }
                return true;

            }
            catch (Exception ex)
            {
                return false;
            }

        }
        /// <summary>
        /// 合并文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task MergeFile(SliceFileInfo file)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload");
            var fileName = file.Name;
            path = path + "//" + fileName + "//";
            string baseFileName = path + fileName.Split("~")[0].ToString();
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var filesList = Directory.GetFiles(Path.GetDirectoryName(path));
            if (filesList.Length != file.Count)
            {
                return;
            }
            List<FileSort> lstFile = new();
            foreach (var item in filesList)
            {
                lstFile.Add(new FileSort()
                {
                    Name = item,
                    NumBer = Convert.ToInt32(item.Substring(item.IndexOf('^') + 1))
                });
            }
            lstFile = lstFile.OrderBy(x => x.NumBer).ToList();
            using (var fileStream = new FileStream(baseFileName, FileMode.Create))
            {
                await Policy.Handle<IOException>()
                        .RetryForeverAsync()
                        .ExecuteAsync(async () =>
                        {
                            foreach (var fileSort in lstFile)
                            {
                                using (FileStream fileChunk = new FileStream(fileSort.Name, FileMode.Open))
                                {
                                    await fileChunk.CopyToAsync(fileStream);
                                }

                            }
                        });


            }
            //删除分片文件
            foreach (var dirfile in filesList)
            {
                System.IO.File.Delete(dirfile);
            }
        }
    }
}
